<?php

/*
 * @desc Emos_Bootstrap_Bootstrap
 */

class Emos_Application_Bootstrap_Bootstrap {

    protected $_option;
    
    protected $_modules;
    
    protected $_url;
    
    protected $_module;

    /**
     * @desc __construct
     * @param type $options 
     */
    public function __construct($options = array()) {
        $this->_url = $this->queryString();
    }

    /**
     * @desc set options with array options
     * @param type $options
     * @return type 
     */
    public function setOptions($options = array()) {
        if (!$options)
            return false;

        $this->_option = $options;

        return $this;
    }

    /**
     * @desc getOptions 
     * @return type 
     */
    public function getOptions() {

        if (!$this->_option)
            return false;

        return $this->_option;
    }

    public function run() {
        $default = $this->getModuleDefault();
        try {
            if ($default) {
                $this->_module = $default;
                $this->loadModule();
                $this->_getReSourceModule($default);
            }

            $this->getResource('FrontController');
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
   
    public function getModule(){
        if (!$this->_module) return false;
        
        return $this->_module;
    }
    
    private function _getReSourceModule($module) {

        if (!$module)
            return;
        $class = ucfirst($module) . '_Controllers_' . (ucfirst($this->_url['controller']) ? ucfirst($this->_url['controller']) . 'Controller' : 'indexController' );

        if (class_exists($class)) {

            $options = array('action' => ($this->_url['action'] ? $this->_url['action'] : 'index'));
            $layout = new $class($options);

            if ($this->_url['action'] && $this->_url['action'] != '' && in_array($this->_url['action'] . 'Action', get_class_methods($layout))) {

                $method = $this->_url['action'] . 'Action';

                $layout->$method();
            } else {
                $layout->init();
            }
            $layout->callAutoRender();
            $this->loadCssJSModule($module);
        } else {
            new Emos_Defaults_Error();
        }
    }

    protected function getResource($name) {

        if (!$name) return false;

        Emos_Views_View::getIntance()->layoutDefault();
    }

    protected function setModuleFolders() {

        $folderModule = APPLICATION_PATH . DS . 'modules';
        $this->_modules = $this->getDirs($folderModule);
    }

    protected function getModuleDefault() {

        $this->setModuleFolders();

        foreach ($this->_modules as $k => $module) {
            if ($module == $this->_url['module']) {
                defined('PATH_MODULE') || define('PATH_MODULE', APPLICATION_PATH . DS . 'modules' . DS . $module);
                return $module;
            }
        }
        return false;
    }

    protected function queryString() {

        $str = explode('/', $_SERVER['PATH_INFO'] ? $_SERVER['PATH_INFO'] : '');
        $str = array_values(array_filter($str));
        if (!$str) {
            new Emos_Defaults_Error();
        }

        foreach ($aryReturn = array(
    'module' => $str[0],
    'controller' => $str[1] ? $str[1] : '',
    'action' => $str[2] ? $str[2] : '',
        ) as $k => $val) {
            if ($val === '')
                unset($aryReturn[$k]);
        }
        return $aryReturn;
    }

    protected function loadModule() {
        if (class_exists('Emos_Loader_Autoloader')) {
            foreach ($this->_modules as $k => $module) {

                new Emos_Loader_Autoloader(array(
                            'base_path' => APPLICATION_PATH . DS . 'modules' . DS . $module,
                            'path' => APPLICATION_PATH . DS . 'modules',
                        ));
            }
        }
        return false;
    }

    public static function getDirs($parentDirectory) {
        if (!$parentDirectory || !file_exists($parentDirectory))
            return array();

        $subDirectory = array();
        $directoryIterator = new DirectoryIterator($parentDirectory);
        foreach ($directoryIterator as $directory) {
            if ($directory->isDot() || !$directory->isDir()) {
                continue;
            }
            $directory = $directory->getFilename();
            if ($directory == '.svn') {
                continue;
            }
            $subDirectory[] = $directory;
        }

        return $subDirectory;
    }

    public function loadCssJSModule($module) {
        if (!$module) return false;
        $jsFolder = 'js';
        $cssFolder = 'css';
        $tempFolder = 'public/template/'. $module;
        $parentDirectory = WEB_ROOT . DS . $tempFolder;
        $baseUrl = Emos_Layout_Layout::getInstance()->baseUrl();
        //load file css
        foreach ($this->getFiles($parentDirectory.DS.$cssFolder) as $k => $css) {
            Emos_Layout_Layout::getInstance()->appendScript($baseUrl.'/'.$tempFolder.'/'.$cssFolder.'/'.$css);
        }
        // load file js
        foreach ($this->getFiles($parentDirectory.DS.$jsFolder) as $k => $js) {
            Emos_Layout_Layout::getInstance()->appendScript($baseUrl.'/'.$tempFolder.'/'.$jsFolder.'/'.$js);
        }
        return true;
    }


        public function getFiles($dir) {
            $styleFiles = array();
            if (is_dir($dir)) {
                $iterators = new DirectoryIterator($dir);
                foreach ($iterators as $file) {
                    if ($file->isDir() || $file->isDot())
                        continue;
                    $name = $file->getFilename();
                    if (preg_match('/^[^a-z]/i', $name) || ('CVS' == $name)
                            || ('.svn' == strtolower($name))) {
                        continue;
                    }
                    $styleFiles[] = $name;
                }
            }
            return $styleFiles;
        }

    

}
